package model

import (
	"common/config"
	"common/helper"
	myUserHelp "common/userHelp"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/shopspring/decimal"
	"github.com/valyala/fasthttp"
	"math"
	"strings"
)

type WithdrawConfigData struct {
	Config TblPayFactory `json:"config"` //提款配置
	//MemberBankList []TblMemberBankcard `json:"member_bank_list"`
	MemberBankT int `json:"member_bank_t"`
	//FreeWithdrawNum int                 `json:"free_withdraw_num" db:"free_withdraw_num" cbor:"free_withdraw_num"` //免费提款次数
	PixId               string  `json:"pix_id" db:"pix_id"`    //上次提现账号
	UnfinishedTotAmount float64 `json:"unfinished_tot_amount"` //还需完成打码
	LockAmount          float64 `json:"lock_amount"`           //未解锁的金额
	WithdrawalFees      float64 `json:"withdrawal_fees"`       //提现手续费
	WithdrawMaxLimit    float64 `json:"withdraw_max_limit"`    //最大提现金额
	WithdrawMinLimit    float64 `json:"withdraw_min_limit"`    //最小提现金额
	AgentWagedTimes     int     `json:"agent_waged_times"`     //代理打码倍数
}

type Bank struct {
	BankCode string
	BankName string
}

// CachePayment 获取支付方式
func CachePayFactory(fid string) (TblPayFactory, error) {

	m := TblPayFactory{}
	query, _, _ := dialect.From("tbl_pay_factory").
		Select(colsPayFactory...).Where(g.Ex{"fid": fid}).ToSQL()
	err := meta.MerchantDB.Get(&m, query)
	if err != nil {
		return m, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}
	return m, nil
}

func ChannelList(fctx *fasthttp.RequestCtx, flags int) (TblPayFactoryData, error) {

	var data TblPayFactoryData
	//data.C = `Prezado usuário, quando o valor da primeira recarga for maior que 50 reais, você receberá no máximo 20% de recompensa de recarga, e quando o valor da recarga for maior que 50 reais, você receberá no máximo 10% de recompensa de recarga! 6 vezes ao dia, quanto maior o valor da recarga, maior a proporção de presentes!`
	query, _, _ := dialect.From("tbl_pay_factory").
		Select(colsPayFactory...).Where(g.Ex{"state": 1, "flags": flags}).Order(g.C("fid").Asc()).ToSQL()

	helper.InfoLog("ChannelList:%s", query)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	for index, _ := range data.D {
		data.D[index].Url = ""
		data.D[index].NotifyUrl = ""
		data.D[index].Key = ""
		data.D[index].Mchid = ""
		data.D[index].AppId = ""
		data.D[index].AppKey = ""
		data.D[index].PayCode = ""
	}

	if len(data.D) == 0 {
		return data, nil
	}
	if flags == 1 {
		uid := GetUidFromToken(fctx)
		if uid == "" {
			return data, errors.New(helper.AccessTokenExpires)
		}
		myUserHelp.LoadUserToRedis(uid)

		var PromoDepositType int = config.PromoDeposit_First
		var pdc []config.PromoDepositConfig
		pdc = config.PromoDepositConfigList(config.PromoDeposit_First)

		if len(pdc) > 0 {
			data.Min = math.MaxFloat64
			data.Max = -math.MaxFloat64
			for _, i := range pdc {
				if i.Bonus != 0 {
					if i.Bonus < data.Min {
						data.Min = i.Bonus
					}
					if i.Bonus > data.Max {
						data.Max = i.Bonus
					}
				}
			}
			if data.Min == math.MaxFloat64 {
				data.Min = 0
			}
			if data.Max == -math.MaxFloat64 {
				data.Max = 0
			}
			data.Max, _ = decimal.NewFromFloat(data.Max).Div(decimal.NewFromInt(100)).Float64()
			data.Min, _ = decimal.NewFromFloat(data.Min).Div(decimal.NewFromInt(100)).Float64()
		}

		TotalDeposit := myUserHelp.GetTotalDeposit(uid)
		if TotalDeposit > 0 {
			pdc = config.PromoDepositConfigList(config.PromoDeposit_Common)
			PromoDepositType = config.PromoDeposit_Common
		}
		for k, v := range data.D {
			al := strings.Split(v.AmountList, ",")
			var ll []DepositAmount
			var discount, bonusAmount decimal.Decimal
			for _, v1 := range al {
				money, _ := decimal.NewFromString(v1)
				for _, v2 := range pdc {
					min := decimal.NewFromFloat(v2.MinAmount)
					max := decimal.NewFromFloat(v2.MaxAmount)
					if money.GreaterThanOrEqual(min) {
						discount = decimal.NewFromFloat(v2.Bonus).Div(decimal.NewFromInt(100))
						// 计算赠送礼金
						bonusAmount = money.Mul(discount)
						if !max.IsZero() && bonusAmount.GreaterThanOrEqual(max) {
							bonusAmount = max
						}
						break
					}
				}

				if PromoDepositType == config.PromoDeposit_First && config.IsActiveOpen(config.ActiveType_FirstCharge_Bonus) == 0 {
					bonusAmount = decimal.NewFromFloat(0.00)
					data.Min = 0
					data.Max = 0
				}

				if PromoDepositType == config.PromoDeposit_Common && config.IsActiveOpen(config.ActiveType_RepeatCharge_Bonus) == 0 {
					bonusAmount = decimal.NewFromFloat(0.00)
					data.Min = 0
					data.Max = 0
				}

				ll = append(ll, DepositAmount{Amount: v1, Discount: bonusAmount.StringFixed(2)})
			}
			data.D[k].AmountArray = ll
		}
	}
	data.T = len(data.D)

	return data, nil
}
